<template>
  <div class="gen-generator-container">
    <!-- ===================== 查询表单 begin ===================== -->
    <el-form :inline="true" :model="queryForm" ref="queryForm" class="demo-form-inline" size="small">
      <el-form-item label="表名" prop="name">
        <el-input v-model.trim="queryForm.name" placeholder="表名" @keyup.enter.native="page"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="page" size="mini">查询</el-button>
        <el-button @click="resetForm('queryForm')" icon="el-icon-refresh" size="mini">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- ===================== 查询表单 end ======================= -->

    <!-- ===================== 操作按钮 begin ===================== -->
    <el-row :gutter="10" class="mb8" style="margin-bottom: 10px; margin-left: 0px; margin-right: 0px">
      <el-button type="primary" icon="el-icon-right" size="mini" @click="importBatch()">导入</el-button>
      <el-button size="mini" @click="toggleSelection()">取消选择</el-button>
    </el-row>
    <!-- ===================== 操作按钮 end ======================= -->

    <!-- ===================== 数据列表 begin ===================== -->
    <el-table
      size="medium"
      class="data-table"
      ref="multipleTable"
      :data="dataTableList"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="name" label="表名"></el-table-column>
      <el-table-column prop="remarks" label="备注" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="400">
        <template slot-scope="scope">
          <el-button type="primary" plain icon="el-icon-right" size="mini" @click="importTable(scope.row)">导入</el-button>
          <el-button plain icon="el-icon-search" @click="detail(scope.row)" size="mini">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- ===================== 数据列表 end ======================= -->

    <!-- ===================== 分页组件 begin ===================== -->
    <pagination v-show="total>0" :total="total" :page.sync="queryForm.pageNumber" :limit.sync="queryForm.pageSize" @pagination="page" />
    <!-- ===================== 分页组件 end ======================= -->

    <!-- ===================== 对话框组件 begin ===================== -->
    <el-dialog
      title="标题"
      width="70%"
      top="5vh"
      :visible.sync="dialogVisible"
      :append-to-body="true">
      <el-table :data="columnList" max-height="650">
        <el-table-column prop="comments" label="列注释"></el-table-column>
        <el-table-column prop="name" label="列名" width="200"></el-table-column>
        <el-table-column prop="columnType" label="列类型"></el-table-column>
        <el-table-column prop="isNull" label="可空">
          <template slot-scope="scope" >{{ scope.row.isNull == '0' ? '否' : '是' }}</template>
        </el-table-column>
        <el-table-column prop="isPk" label="是否主键">
          <template slot-scope="scope" >{{ scope.row.isPk == '0' ? '' : '主键' }}</template>
        </el-table-column>
        <!--<el-table-column prop="jdbcType" label="JDBC类型"></el-table-column>
        <el-table-column prop="javaType" label="JAVA类型"></el-table-column>
        <el-table-column prop="javaField" label="JAVA字段名"></el-table-column>
        <el-table-column prop="valueLength" label="长度"></el-table-column>
        <el-table-column prop="intAccuracy" label="精度"></el-table-column>
        <el-table-column prop="sort" label="排序"></el-table-column>-->
      </el-table>
      <!-- 这里的内容会替换 title -->
      <span slot="title" class="dialog-footer">{{dialogTitle}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain icon="el-icon-close" @click="dialogVisible = false" size="medium">关 闭</el-button>
        <el-button type="primary" icon="el-icon-news" @click="importTable(dataTable)" size="medium">导 入</el-button>
      </span>
    </el-dialog>
    <!-- ===================== 对话框组件 end ======================= -->
  </div>
</template>

<script>
import { getDataTableList, getDataTableColumnList, importTableBatch } from '@/api/gen'
import { errorMsg, successMsg } from '@/api/message'
import Pagination from '@/components/Pagination/index'

export default {
  name: 'DataTable',
  components: {
    Pagination
  },
  props: {},
  data () {
    return {
      // 数据总数
      total: 0,
      // 查询表单 Model
      queryForm: {
        name: '',
        remarks: '',
        pageNumber: 1,
        pageSize: 10
      },
      // 表 List Model
      dataTableList: [],
      // 表 List Model
      dataTable: {
        name: '',
        remarks: ''
      },
      // 列 List Model
      columnList: [],
      // 列实体 Model
      column: {
        name: '', // 列名
        comments: '', // 列注释
        isPk: '', // 是否主键（1：主键）
        jdbcType: '', // JDBC类型（大写）
        columnType: '', // 列类型（JDBC类型+长度）
        valueLength: '', // 长度
        intAccuracy: '', // 整数精度（小数点多少位）
        javaType: '', // JAVA类型
        javaField: '', // JAVA字段名
        isNull: '', // 是否可为空（1：可为空；0：不为空）
        sort: '' // 排序（升序）
      },
      // 勾选的表
      selectedTableList: [],
      // 对话框是否显示
      dialogVisible: false,
      // 对话框 title
      dialogTitle: ''
    }
  },
  computed: {},
  watch: {},
  created () {
    this.page()
  },
  mounted () {},
  methods: {
    /* ========== 表单重置 ========== */
    resetForm (formName) {
      // 元素必须设置 prop 属性才会生效
      this.$refs[formName].resetFields()
      this.page()
    },
    /* ========== 表单重置 ========== */

    /* ========== 分页查询 ========== */
    page () {
      // 获取表单绑定数据
      const vm = this
      // 展示 loading
      const loading = vm.doLoading()
      // 执行查询
      getDataTableList(vm.queryForm).then(res => {
        vm.dataTableList = res.data.data.list
        vm.total = res.data.data.total
      }).catch(err => {
        errorMsg(err)
      })

      // 关闭 loading
      loading.close()
    },
    /* ========== 分页查询 ========== */

    /* ==========loading 加载动画 ========== */
    doLoading () {
      const loading = this.$loading({
        target: '.data-table',
        lock: true,
        text: '拼命加载数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return loading
    },
    /* ==========loading 加载动画 ========== */

    /* 勾选表（列表当选择项发生变化时会触发该事件） */
    handleSelectionChange (row) {
      // 这里会将所有选择的行通过 row 传进来
      this.selectedTableList = row
    },
    /* 勾选表（列表当选择项发生变化时会触发该事件） */

    /* ========== 批量导入 ========== */
    importBatch () {
      const vm = this
      if (vm.selectedTableList.length === 0) {
        vm.$message.error('请勾选要导入的表')
        return false
      }

      // 解析勾选的表 id，保存到 ids
      const names = []
      for (let i = 0; i < vm.selectedTableList.length; i++) {
        const name = vm.selectedTableList[i].name
        names.push(name)
      }
      importTableBatch(names).then(res => {
        // 生成成功，清空勾选的表
        this.$refs.multipleTable.clearSelection()
        successMsg(vm, res.data.message)
      }).catch(err => {
        // 查询失败处理
        errorMsg(err)
      })
    },
    /* ========== 批量导入 ========== */

    /* ========== 导入 ========== */
    importTable (row) {
      const vm = this
      const names = [row.name]
      importTableBatch(names).then(res => {
        // 生成成功，清空勾选的表
        this.$refs.multipleTable.clearSelection()
        successMsg(vm, res.data.message)
      }).catch(err => {
        // 查询失败处理
        errorMsg(err)
      })
    },
    /* ========== 导入 ========== */

    /*  ========== 查看 ========== */
    detail (row) {
      const vm = this
      // 打开对话框
      vm.dialogVisible = true
      vm.dataTable = row
      // 设置对话框标题
      vm.dialogTitle = row.name + ' ' + row.remarks
      getDataTableColumnList(row.name).then(res => {
        // 查询成功，渲染数据
        vm.columnList = res.data.data
      }).catch(err => {
        // 查询失败处理
        errorMsg(err)
      })
    },
    /*  ========== 查看 ========== */

    /* 关闭对话框提示 */
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },

    /* ========== 取消勾选 ========== */
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    }
    /* ========== 取消勾选 ========== */
  }
}
</script>

<style scoped lang="less"></style>
